<template>
  <!--  报工记录-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" :rules="formRules" ref="searchForm" class="demo-form-inline"  @submit.native.prevent="submitForm()">
        <el-form-item style="display: none;">
          <button type="submit"></button>
        </el-form-item>
        <el-form-item label="工单号">
          <el-input v-model="searchParam.workNo" placeholder="请输入工单号" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="产出物料名称">
          <el-input v-model="searchParam.materialOutName" placeholder="请输入产出物料名称" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="设备">
          <el-select v-model="searchParam.equipmentId" placeholder="请选择设备" clearable filterable remote reserve-keyword
                     :remote-method="remoteEquipment" style="width: 200px">
            <el-option v-for="item in equipmentOptions" :key="item.id" :label="item.equipmentCode" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="searchParam.reportWorkRecordNo" placeholder="请输入批次号" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="工序名称">
          <el-input v-model="searchParam.procedureName" placeholder="请输入工序名称" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="报工时间">
          <el-date-picker v-model="searchParam.times" type="datetimerange" range-separator="-"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          start-placeholder="报工开始时间" end-placeholder="报工结束时间"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="submitForm()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
                     style="margin-left: 10px;">导出
          </el-button>
          <el-button type="primary" @click="printBoxClick" :disabled="multipleSelection.length == 0"
                     v-if="currentPath==='/scheduling/workReportTecord'">报工总数打印
          </el-button>
          <el-button type="primary" @click="printCodeClick" :disabled="multipleSelection.length == 0"
                     v-if="currentPath==='/scheduling/workReportTecord'">追溯码补打
          </el-button>
          <el-button @click="revokeJob" type="primary"
                     v-if="currentPath==='/scheduling/workReportTecord'"
                     :disabled="multipleSelection.length != 1 || multipleSelection[0].isRevocation">撤销报工
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 370px)"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"
                         v-if="currentPath==='/scheduling/workReportTecord'"/>
        <el-table-column label="序号" align="center" width="70" fixed>
          <template #default="scope"> {{ (pageSearch.current - 1) * pageSearch.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="workNo" label="工单号" align="center" min-width="250" fixed/>
        <el-table-column prop="materialOutName" label="产出物料名称" align="center" min-width="250" show-overflow-tooltip/>
        <el-table-column prop="count" label="报工数量" align="center" min-width="200"/>
        <el-table-column prop="equipmentCode" label="设备编码" align="center" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="equipmentName" label="设备名称" align="center" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="planProcedureOrderNo" label="工序订单号" align="center" min-width="200"/>
        <el-table-column prop="reportWorkRecordNo" label="批次号" align="center" min-width="200"/>
        <el-table-column prop="isRevocation" label="是否撤销报工" align="center" min-width="200" show-overflow-tooltip>
          <template #default="scope"> {{ scope.row.isRevocation ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="basicUnit" label="单位" align="center" min-width="200"/>
        <el-table-column prop="procedureName" label="工序名称" align="center" min-width="250" show-overflow-tooltip/>
        <el-table-column prop="reportTraceCode" label="追溯码" align="center" min-width="300"/>
        <el-table-column prop="reportUser" label="报工人" align="center" min-width="120"/>
        <el-table-column prop="reportTime" label="报工时间" align="center" min-width="200"/>
        <el-table-column prop="status" label="物料状态" :formatter="statusType" align="center" min-width="200"/>
        <el-table-column prop="createTime" label="创建时间"  align="center" min-width="200"/>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
                       :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {computed, ref, onMounted, getCurrentInstance} from 'vue';
import {ElMessage, ElForm, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus, Refresh, Search} from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import {useRoute} from 'vue-router';
import axios from "axios";
import moment from "moment";

const route = useRoute();

// 当前路由的路径
const currentPath = route.path;
console.log(currentPath, '/scheduling/workReportTecord');

onMounted(() => {
  getList();
  getOption();
});

const multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const searchForm = ref<InstanceType<typeof ElForm>>();

const pageSearch = ref({
  current: 1,
  pageSize: 10
});
const statusType = (e) => {
  const list = [{
    label: '不合格',
    value: '0'
  }, {
    label: '合格',
    value: '1'
  }, {
    label: '报废',
    value: '2'
  }];
  const type = list.find(type => type.value == e.status);
  return type ? type.label : '';
};
const pageTotal = ref(null); // 页面总数
const searchParam = ref({
  times: [
    dayjs().subtract(1, 'month').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().format('YYYY-MM-DD HH:mm:ss')
  ]
});

const paginatedData = ref([]);
const workRoomList = ref([]); // 车间
const equipmentData = ref([]);

const formRules = ref({
  organizationId: [{required: true, message: '请选择工厂/车间', trigger: 'change'}],
  equipmentIds: [{required: true, message: '请选择设备', trigger: 'change'}]
});

const handleOrganizationChange = (value) => {
  axiosInstance.post('/api/basedataEquipment/getAll', {organizationId: value}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    equipmentData.value = res.data;
  });
};

const downLoading = ref(false);
const handleExport = () => {
  downLoading.value = true;
  axios.post('/api/planOrder/reportWorkRecordReportExcel', {
    ...searchParam.value,
    startDate: searchParam.value?.times?.[0],
    endDate: searchParam.value?.times?.[1],
    times: undefined
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      Userid: localStorage.getItem('tokenUserId'),
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', '报工记录表' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};


const equipmentOptions = ref([]);


const getOption = () => {
  axiosInstance.post('/api/basedataOrganization/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });

  axiosInstance.post('/api/basedataEquipment/getPage', {
    current: 1,
    pageSize: 50
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        equipmentOptions.value = res.data.records;
      });
};


const {proxy}: any = getCurrentInstance();
// 箱码
const printBoxClick = () => {
  const templateName = 'test_print1/reportWorkSupplementTemplate.cpt';
  proxy.$printClick(templateName, multipleSelection.value);
};

const printCodeClick = () => {
  const templateName = '/test_print1/ReportTraceCodePrints.cpt';
  proxy.$printClick(templateName, multipleSelection.value);
};


const revokeJob = () => {
  ElMessageBox.confirm('是否确认撤销报工?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        const param = multipleSelection.value[0];
        axiosInstance.post('/api/workOrder/revocationWork',
            {id: param.id}
        ).then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功');
          getList();
        });
      });
};

const remoteEquipment = (value) => {
  if (!value) {
    return;
  }
  axiosInstance.post('/api/basedataEquipment/getPage', {
    current: 1,
    pageSize: 50,
    equipmentCode: value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        equipmentOptions.value = res.data.records;
      });
};

// 获取列表接口
const getList = () => {
  axiosInstance.post('/api/planOrder/reportWorkRecordReport', {
    ...searchParam.value,
    startDate: searchParam.value?.times?.[0],
    endDate: searchParam.value?.times?.[1],
    times: undefined,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 提交表单
const submitForm = () => {
  searchForm.value.validate((valid) => {
    if (valid) {
      getList();
    } else {
      ElMessage.error('请检查表单输入');
      return false;
    }
  });
};

// 重置搜索条件
const resetSearch = () => {
  pageSearch.value.current = 1;
  searchForm.value.clearValidate();
  searchParam.value = {
    times: []
  };
  submitForm();
};
</script>
<style scoped></style>